package com.fau.wmbj.server.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 管理员角色
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2023-03-08 17:18
 */
@Getter
@Setter
@Entity(name = "f_role")
@org.hibernate.annotations.Table(appliesTo = "f_role", comment = "角色")
public class Role extends BaseEntity<Long> implements Serializable {

    /**
     * 标识符
     */
    @Column(name = "code_", unique = true)
    private String code;

    /**
     * 名称
     */
    @Column(name = "name", nullable = false)
    private String name;

    /**
     * 描述
     */
    @Column(name = "desc_",length = 500)
    private String desc;

    /**
     * 所属公司
     */
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "company_id")
    private Company company;

    /**
     * 用户
     */
    @JsonIgnore
    @OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<User> users = new ArrayList<>();

    /**
     * 权限
     */
    @JsonIgnore
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "f_role_menu", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "menu_id"))
    @OrderBy(" order asc ")
    private Set<Menu> menus = new HashSet<>();

    @Transient
    private Long[] ids;

    /**
     * 删除前处理
     */
    @PreRemove
    public void preRemove() {
        Set<Menu> menuSet = getMenus();
        if (menuSet != null) {
            for (Menu menu : menuSet) {
                menu.getRoles().remove(this);
            }
        }
    }

}
